<template>
  <div class="room-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="left-actions">
        <el-button type="primary" @click="showRoomDialog = true">
          <el-icon><Plus /></el-icon>
          新增房间
        </el-button>
        <el-button type="success" @click="showRoomTypeDialog = true">
          <el-icon><OfficeBuilding /></el-icon>
          房型管理
        </el-button>
        <el-button type="warning" @click="batchUpdateStatus">
          <el-icon><Edit /></el-icon>
          批量操作
        </el-button>
      </div>
      <div class="right-actions">
        <el-select v-model="filterStatus" placeholder="房间状态" style="width: 120px" clearable>
          <el-option label="全部" value="" />
          <el-option label="可用" value="available" />
          <el-option label="占用" value="occupied" />
          <el-option label="清洁中" value="cleaning" />
          <el-option label="维修中" value="maintenance" />
          <el-option label="停用" value="disabled" />
        </el-select>
        <el-select v-model="filterFloor" placeholder="楼层" style="width: 100px" clearable>
          <el-option v-for="floor in floors" :key="floor" :label="`${floor}楼`" :value="floor" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索房间号、房型"
          style="width: 200px"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="4">
        <div class="stat-card available">
          <div class="stat-number">{{ roomStats.available }}</div>
          <div class="stat-label">可用房间</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-card occupied">
          <div class="stat-number">{{ roomStats.occupied }}</div>
          <div class="stat-label">占用房间</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-card cleaning">
          <div class="stat-number">{{ roomStats.cleaning }}</div>
          <div class="stat-label">清洁中</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-card maintenance">
          <div class="stat-number">{{ roomStats.maintenance }}</div>
          <div class="stat-label">维修中</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-card disabled">
          <div class="stat-number">{{ roomStats.disabled }}</div>
          <div class="stat-label">停用房间</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="stat-card total">
          <div class="stat-number">{{ roomStats.total }}</div>
          <div class="stat-label">总房间数</div>
        </div>
      </el-col>
    </el-row>

    <!-- 房间网格视图 -->
    <el-card class="room-grid-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">房间分布图</span>
          <div class="view-controls">
            <el-radio-group v-model="viewMode" size="small">
              <el-radio-button label="grid">网格视图</el-radio-button>
              <el-radio-button label="list">列表视图</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="room-grid">
        <div v-for="floor in sortedFloors" :key="floor" class="floor-section">
          <div class="floor-header">
            <h3>{{ floor }}楼</h3>
            <div class="floor-stats">
              <span>总计: {{ getFloorRooms(floor).length }}</span>
              <span>可用: {{ getFloorAvailableCount(floor) }}</span>
            </div>
          </div>
          <div class="room-row">
            <div
              v-for="room in getFloorRooms(floor)"
              :key="room.id"
              class="room-card"
              :class="[
                `status-${room.status}`,
                { selected: selectedRooms.includes(room.id) }
              ]"
              @click="toggleRoomSelection(room)"
              @contextmenu.prevent="showRoomContextMenu(room, $event)"
            >
              <div class="room-number">{{ room.roomNumber }}</div>
              <div class="room-type">{{ room.roomTypeName }}</div>
              <div class="room-status">
                <el-tag :type="getStatusType(room.status)" size="small">
                  {{ getStatusText(room.status) }}
                </el-tag>
              </div>
              <div v-if="room.guestName" class="guest-info">
                <div class="guest-name">{{ room.guestName }}</div>
                <div class="checkout-time">{{ formatTime(room.checkoutTime) }}</div>
              </div>
              <div class="room-price">¥{{ room.price }}/晚</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-else class="room-list">
        <el-table
          :data="filteredRooms"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          row-key="id"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="roomNumber" label="房间号" width="100" sortable />
          <el-table-column prop="floor" label="楼层" width="80" sortable />
          <el-table-column prop="roomTypeName" label="房型" width="120" />
          <el-table-column prop="bedType" label="床型" width="100" />
          <el-table-column prop="maxOccupancy" label="最大入住" width="100" />
          <el-table-column prop="price" label="价格" width="100">
            <template #default="{ row }">
              ¥{{ row.price }}/晚
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="guestName" label="客人" width="100" />
          <el-table-column prop="checkoutTime" label="退房时间" width="150">
            <template #default="{ row }">
              {{ row.checkoutTime ? formatDateTime(row.checkoutTime) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="lastCleanTime" label="最后清洁" width="150">
            <template #default="{ row }">
              {{ row.lastCleanTime ? formatDateTime(row.lastCleanTime) : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="editRoom(row)">
                编辑
              </el-button>
              <el-dropdown @command="handleRoomAction">
                <el-button type="text" size="small">
                  更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{ action: 'clean', room: row }">
                      标记清洁完成
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'maintenance', room: row }">
                      标记维修完成
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'disable', room: row }">
                      停用房间
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'enable', room: row }">
                      启用房间
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'delete', room: row }" divided>
                      删除房间
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 房间对话框 -->
    <RoomDialog
      v-model="showRoomDialog"
      :room="selectedRoom"
      @success="handleRoomSuccess"
    />

    <!-- 房型管理对话框 -->
    <RoomTypeDialog
      v-model="showRoomTypeDialog"
      @success="handleRoomTypeSuccess"
    />

    <!-- 右键菜单 -->
    <el-dropdown
      ref="contextMenuRef"
      trigger="contextmenu"
      :virtual-ref="contextMenuVirtualRef"
      virtual-triggering
    >
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="editRoom(contextMenuRoom)">
            编辑房间
          </el-dropdown-item>
          <el-dropdown-item @click="changeRoomStatus(contextMenuRoom, 'available')">
            设为可用
          </el-dropdown-item>
          <el-dropdown-item @click="changeRoomStatus(contextMenuRoom, 'cleaning')">
            设为清洁中
          </el-dropdown-item>
          <el-dropdown-item @click="changeRoomStatus(contextMenuRoom, 'maintenance')">
            设为维修中
          </el-dropdown-item>
          <el-dropdown-item @click="changeRoomStatus(contextMenuRoom, 'disabled')">
            停用房间
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  OfficeBuilding,
  Edit,
  Search,
  Refresh,
  ArrowDown
} from '@element-plus/icons-vue'
import RoomDialog from './components/RoomDialog.vue'
import RoomTypeDialog from './components/RoomTypeDialog.vue'
import { getRoomList, getRoomStats, updateRoomStatus } from '@/api/room'
import dayjs from 'dayjs'

// 响应式数据
const viewMode = ref('grid')
const searchKeyword = ref('')
const filterStatus = ref('')
const filterFloor = ref('')
const showRoomDialog = ref(false)
const showRoomTypeDialog = ref(false)
const selectedRoom = ref(null)
const selectedRooms = ref([])
const contextMenuRef = ref()
const contextMenuVirtualRef = ref()
const contextMenuRoom = ref(null)

// 房间统计
const roomStats = reactive({
  available: 45,
  occupied: 38,
  cleaning: 8,
  maintenance: 3,
  disabled: 2,
  total: 96
})

// 房间列表
const roomList = ref([
  {
    id: 1,
    roomNumber: '101',
    floor: 1,
    roomTypeId: 1,
    roomTypeName: '标准单人间',
    bedType: '单人床',
    maxOccupancy: 1,
    price: 288,
    status: 'available',
    guestName: null,
    checkoutTime: null,
    lastCleanTime: new Date()
  },
  {
    id: 2,
    roomNumber: '102',
    floor: 1,
    roomTypeId: 2,
    roomTypeName: '标准双人间',
    bedType: '双人床',
    maxOccupancy: 2,
    price: 388,
    status: 'occupied',
    guestName: '张三',
    checkoutTime: new Date(Date.now() + 24 * 60 * 60 * 1000),
    lastCleanTime: new Date(Date.now() - 24 * 60 * 60 * 1000)
  },
  {
    id: 3,
    roomNumber: '103',
    floor: 1,
    roomTypeId: 3,
    roomTypeName: '商务套房',
    bedType: '大床',
    maxOccupancy: 2,
    price: 588,
    status: 'cleaning',
    guestName: null,
    checkoutTime: null,
    lastCleanTime: null
  },
  {
    id: 4,
    roomNumber: '201',
    floor: 2,
    roomTypeId: 1,
    roomTypeName: '标准单人间',
    bedType: '单人床',
    maxOccupancy: 1,
    price: 288,
    status: 'maintenance',
    guestName: null,
    checkoutTime: null,
    lastCleanTime: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000)
  },
  {
    id: 5,
    roomNumber: '301',
    floor: 3,
    roomTypeId: 4,
    roomTypeName: '豪华套房',
    bedType: '大床',
    maxOccupancy: 3,
    price: 888,
    status: 'occupied',
    guestName: '李四',
    checkoutTime: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000),
    lastCleanTime: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000)
  }
])

// 计算属性
const floors = computed(() => {
  const floorSet = new Set(roomList.value.map(room => room.floor))
  return Array.from(floorSet).sort((a, b) => a - b)
})

const sortedFloors = computed(() => {
  return floors.value.sort((a, b) => b - a) // 从高楼层到低楼层
})

const filteredRooms = computed(() => {
  let filtered = roomList.value
  
  // 按状态过滤
  if (filterStatus.value) {
    filtered = filtered.filter(room => room.status === filterStatus.value)
  }
  
  // 按楼层过滤
  if (filterFloor.value) {
    filtered = filtered.filter(room => room.floor === filterFloor.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(room => 
      room.roomNumber.toLowerCase().includes(keyword) ||
      room.roomTypeName.toLowerCase().includes(keyword)
    )
  }
  
  return filtered
})

// 方法
const getFloorRooms = (floor) => {
  return filteredRooms.value.filter(room => room.floor === floor)
}

const getFloorAvailableCount = (floor) => {
  return getFloorRooms(floor).filter(room => room.status === 'available').length
}

const getStatusType = (status) => {
  const statusMap = {
    available: 'success',
    occupied: 'warning',
    cleaning: 'info',
    maintenance: 'danger',
    disabled: ''
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    available: '可用',
    occupied: '占用',
    cleaning: '清洁中',
    maintenance: '维修中',
    disabled: '停用'
  }
  return statusMap[status] || '未知'
}

const formatTime = (time) => {
  return time ? dayjs(time).format('MM-DD HH:mm') : ''
}

const formatDateTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm') : ''
}

const toggleRoomSelection = (room) => {
  const index = selectedRooms.value.indexOf(room.id)
  if (index > -1) {
    selectedRooms.value.splice(index, 1)
  } else {
    selectedRooms.value.push(room.id)
  }
}

const handleSelectionChange = (selection) => {
  selectedRooms.value = selection.map(room => room.id)
}

const showRoomContextMenu = (room, event) => {
  contextMenuRoom.value = room
  contextMenuVirtualRef.value = {
    getBoundingClientRect() {
      return {
        width: 0,
        height: 0,
        top: event.clientY,
        left: event.clientX
      }
    }
  }
}

const editRoom = (room) => {
  selectedRoom.value = room
  showRoomDialog.value = true
}

const changeRoomStatus = async (room, status) => {
  try {
    await updateRoomStatus(room.id, status)
    room.status = status
    ElMessage.success('房间状态已更新')
    await loadRoomStats()
  } catch (error) {
    ElMessage.error('更新房间状态失败')
  }
}

const handleRoomAction = async ({ action, room }) => {
  switch (action) {
    case 'clean':
      await changeRoomStatus(room, 'available')
      room.lastCleanTime = new Date()
      break
    case 'maintenance':
      await changeRoomStatus(room, 'available')
      break
    case 'disable':
      await changeRoomStatus(room, 'disabled')
      break
    case 'enable':
      await changeRoomStatus(room, 'available')
      break
    case 'delete':
      await deleteRoom(room)
      break
  }
}

const deleteRoom = async (room) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除房间 ${room.roomNumber} 吗？此操作不可恢复。`,
      '删除房间',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    const index = roomList.value.findIndex(r => r.id === room.id)
    if (index > -1) {
      roomList.value.splice(index, 1)
    }
    
    ElMessage.success('房间已删除')
    await loadRoomStats()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除房间失败')
    }
  }
}

const batchUpdateStatus = async () => {
  if (selectedRooms.value.length === 0) {
    ElMessage.warning('请先选择要操作的房间')
    return
  }
  
  try {
    const { value: status } = await ElMessageBox.prompt(
      '请选择要设置的状态',
      '批量更新状态',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'select',
        inputOptions: {
          available: '可用',
          cleaning: '清洁中',
          maintenance: '维修中',
          disabled: '停用'
        }
      }
    )
    
    // 批量更新状态
    selectedRooms.value.forEach(roomId => {
      const room = roomList.value.find(r => r.id === roomId)
      if (room) {
        room.status = status
      }
    })
    
    selectedRooms.value = []
    ElMessage.success('批量更新成功')
    await loadRoomStats()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量更新失败')
    }
  }
}

const refreshData = async () => {
  try {
    await loadData()
    ElMessage.success('数据已刷新')
  } catch (error) {
    ElMessage.error('刷新失败')
  }
}

const handleRoomSuccess = () => {
  showRoomDialog.value = false
  selectedRoom.value = null
  refreshData()
}

const handleRoomTypeSuccess = () => {
  showRoomTypeDialog.value = false
  refreshData()
}

const loadRoomStats = async () => {
  try {
    // const stats = await getRoomStats()
    // Object.assign(roomStats, stats)
    
    // 临时计算统计数据
    const stats = {
      available: roomList.value.filter(r => r.status === 'available').length,
      occupied: roomList.value.filter(r => r.status === 'occupied').length,
      cleaning: roomList.value.filter(r => r.status === 'cleaning').length,
      maintenance: roomList.value.filter(r => r.status === 'maintenance').length,
      disabled: roomList.value.filter(r => r.status === 'disabled').length,
      total: roomList.value.length
    }
    Object.assign(roomStats, stats)
  } catch (error) {
    console.error('加载房间统计失败:', error)
  }
}

const loadData = async () => {
  try {
    // 加载房间列表
    // const rooms = await getRoomList()
    // roomList.value = rooms
    
    // 加载统计数据
    await loadRoomStats()
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.room-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 84px);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  .left-actions {
    display: flex;
    gap: 12px;
  }
  
  .right-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }
  
  .stat-number {
    font-size: 32px;
    font-weight: 600;
    margin-bottom: 8px;
  }
  
  .stat-label {
    font-size: 14px;
    color: var(--el-text-color-regular);
  }
  
  &.available {
    .stat-number {
      color: #67c23a;
    }
  }
  
  &.occupied {
    .stat-number {
      color: #e6a23c;
    }
  }
  
  &.cleaning {
    .stat-number {
      color: #409eff;
    }
  }
  
  &.maintenance {
    .stat-number {
      color: #f56c6c;
    }
  }
  
  &.disabled {
    .stat-number {
      color: #909399;
    }
  }
  
  &.total {
    .stat-number {
      color: var(--el-text-color-primary);
    }
  }
}

.room-grid-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
}

.room-grid {
  .floor-section {
    margin-bottom: 30px;
    
    .floor-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 2px solid var(--el-border-color);
      
      h3 {
        margin: 0;
        color: var(--el-text-color-primary);
      }
      
      .floor-stats {
        display: flex;
        gap: 16px;
        font-size: 14px;
        color: var(--el-text-color-regular);
      }
    }
    
    .room-row {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 16px;
    }
  }
}

.room-card {
  background: white;
  border: 2px solid var(--el-border-color);
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }
  
  &.selected {
    border-color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);
  }
  
  .room-number {
    font-size: 20px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin-bottom: 8px;
  }
  
  .room-type {
    font-size: 14px;
    color: var(--el-text-color-regular);
    margin-bottom: 8px;
  }
  
  .room-status {
    margin-bottom: 8px;
  }
  
  .guest-info {
    margin-bottom: 8px;
    
    .guest-name {
      font-size: 14px;
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 2px;
    }
    
    .checkout-time {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
  }
  
  .room-price {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-color-primary);
  }
  
  // 状态样式
  &.status-available {
    border-color: #67c23a;
    
    &:hover {
      border-color: #529b2e;
    }
  }
  
  &.status-occupied {
    border-color: #e6a23c;
    
    &:hover {
      border-color: #b88230;
    }
  }
  
  &.status-cleaning {
    border-color: #409eff;
    
    &:hover {
      border-color: #337ecc;
    }
  }
  
  &.status-maintenance {
    border-color: #f56c6c;
    
    &:hover {
      border-color: #c45656;
    }
  }
  
  &.status-disabled {
    border-color: #909399;
    background-color: #f5f7fa;
    
    &:hover {
      border-color: #73767a;
    }
  }
}

.room-list {
  .el-table {
    border-radius: 8px;
    overflow: hidden;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .room-grid {
    .room-row {
      grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    }
  }
}

@media (max-width: 768px) {
  .room-container {
    padding: 10px;
  }
  
  .operation-bar {
    flex-direction: column;
    gap: 16px;
    
    .left-actions,
    .right-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }
  
  .stats-cards {
    .el-col {
      margin-bottom: 12px;
    }
  }
  
  .room-grid {
    .room-row {
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      gap: 12px;
    }
  }
  
  .room-card {
    padding: 12px;
    
    .room-number {
      font-size: 18px;
    }
  }
}
</style>